package com.tcpengine.net;

import com.tcpengine.client.LogView;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;

// 网络服务
public class NetService {
	
	public static int WS_TYPE = 1;
	public static int TCP_TYPE = 2;
	
	private WsClient m_wsClient = null;
	private TcpClient m_tcpClient = null;
	private LogView m_logView = null;
	
	public NetService(LogView logView) {
		m_logView = logView;
	}
	
	public void connect(int netType, String strUrl) {
		// m_wsClient = new WsClient(m_logView);
		if(strUrl.isEmpty()) {
			m_logView.println("网络地址不能是空");
		}
		if(NetService.WS_TYPE == netType) {
			m_wsClient = new WsClient(m_logView);
			m_tcpClient = null;
			try {
				m_wsClient.wsConnect(strUrl);
				
			} catch (Exception e) {
				// e.printStackTrace();
				m_logView.println("连接websocket服务器异常失败 : " + e.getMessage());
			}
		}
		else {
			m_tcpClient = new TcpClient(m_logView);
			m_wsClient = null;
			m_tcpClient.tcpConnect(strUrl);
		}
	}
	
	// 发送登陆数据
	public void sendLogin() {
		m_logView.println("websocket发送登陆消息");
		byte[] arrPwd = "password".getBytes();
		int len = 4 + arrPwd.length;
		ByteBuf byteBuf = Unpooled.buffer(len);
		
		byteBuf.writeInt(8888);		// 登陆帐号, 四个字节
		byteBuf.writeBytes(arrPwd);	// 登陆密码
		Msg msg = new Msg(1000, len, byteBuf);
		
		if(null != m_wsClient) {
			m_wsClient.sendMessage(msg);
		}
		else if(null != m_tcpClient) {
			m_tcpClient.sendMessage(msg);
		}
	}
	
	// 查询用户信息
	public void queryUserInfo() {
		Msg msg = new Msg(1001, 0, null);
		if(null != m_wsClient) {
			m_wsClient.sendMessage(msg);
		}
		else if(null != m_tcpClient) {
			m_tcpClient.sendMessage(msg);
		}
	}
	
	public void send1002() {
		
		byte[] arrPwd = "特殊格式消息体".getBytes();
		int len = arrPwd.length;
		ByteBuf byteBuf = Unpooled.buffer(len);
		byteBuf.writeBytes(arrPwd);	// 登陆密码
		Msg msg = new Msg(1002, len, byteBuf);
		
		if(null != m_wsClient) {
			m_wsClient.sendMessage(msg);
		}
		else if(null != m_tcpClient) {
			m_tcpClient.sendMessage(msg);
		}
	}
	
	
}
